﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using EzFrameWork;
namespace EzFrameWork
{
    /// <summary>
    /// 存储每一行的元素
    /// </summary>
    public class Csvline
    {
        List<string> Items;
        public Csvline(string[] lie)
        {
            Items = new List<string>();
            for (int i = 0; i < lie.Length; i++)
            {
                Items.Add(lie[i]);
            }
        }

        /// <summary>
        /// 通过索引获取元素
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string GetItemForIndex(int index)
        {
            int realIndex = index - 1;
            return Items[realIndex];
        }
    }

    public class EzCsv
    {
        private string path;
        private string fileData;

        //private List<string> hangList = new List<string>();
        private List<Csvline> csvlines = new List<Csvline>();

        public string CSVPath
        {
            get
            {
                return path;
            }
        }

        public EzCsv()
        {

        }

        public EzCsv(string path, Encoding encoding)
        {
            if (File.Exists(path))
            {
                this.path = path;
                fileData = EzDataRWS.TxtFileRead(path, encoding);
                ReadData();
                Debug.Log("成功读取表格");
            }
            else
            {
                Debug.LogError(path + "是个无效的路径。");
            }
        }

        private void ReadData()
        {
            string[] hang = fileData.Split('\n');
            for (int i = 0; i < hang.Length - 1; i++)
            {
                string[] items = hang[i].Split(',');//拆分每行数据
                Csvline hangCsv = new Csvline(items);
                csvlines.Add(hangCsv);
            }
        }

        /// <summary>
        /// 通过索引获取数据
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public string GetDataFormIndex(int x, int y)
        {
            int realX = x - 1;
            return csvlines[realX].GetItemForIndex(y);
        }
        public int CsvlineCount
        {
            get
            {
                return csvlines.Count;
            }
        }
    }
}
